import wx
import wx.grid
import wx.gizmos as gizmos
import wx.html2 as web

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import winreg as _winreg, sys

class HtmlPanel(wx.Panel):
    def __init__(self,parent,id=-1):
        super(HtmlPanel, self).__init__(parent,id)

        self.key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                                   r"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",
                                   0, _winreg.KEY_ALL_ACCESS)
        try:
            # 设置注册表python.exe 值为 11000(IE11)
            _winreg.SetValueEx(self.key, 'python.exe', 0, _winreg.REG_DWORD, 0x00002af8)
        except:
            # 设置出现错误
            print('error in set value!')

        vbox = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(vbox)
        self.browser = web.WebView.New(self)
        vbox.Add(self.browser, proportion=-1, flag=wx.EXPAND | wx.ALL, border=10)

        self.Bind(wx.EVT_CLOSE, self.OnClose)

    def OnClose(self, evt):
        print('close')
        # 用完取消注册表设置
        _winreg.DeleteValue(self.key, 'python.exe')
        # 关闭打开的注册表
        _winreg.CloseKey(self.key)
        evt.Skip()

    def show_file(self, file):
        #self.browser.LoadURL('http://www.36kr.com')

        with open(file, 'r') as f:
            html_cont = f.read()
            self.browser.SetPage(html_cont, "")
            self.browser.Show()



class AiTreeListCtrl(gizmos.TreeListCtrl):
    def __init__(self, parent=None, id=-1, pos=(0, 0), size=wx.DefaultSize,
                 style=wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT, cols= [],root_text=''):

        wx.gizmos.TreeListCtrl.__init__(self, parent, id, pos, size, style)
        self.root = None
        self.init_ui(cols, root_text)
        self.root = self.AddRoot(root_text)

    def init_ui(self, cols,root_text):

        self.images = wx.ImageList(16, 16, True)
        self.images.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, (16, 16)))
        self.images.Add(wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, (16, 16)))
        self.images.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, (16, 16)))
        self.SetImageList(self.images)
        #self.root = self.AddRoot(root_text)


        self.cols = cols
        for i, col in enumerate(cols):
            self.AddColumn(col)
            self.SetColumnWidth(i, 150)

    def show_datas(self,item_datas):
        for key, items in item_datas.items():
            item = self.AppendItem(self.root, key)
            self.SetItemText(item, key + " (共" + str(len(items)) + "项)", 0)
            self.SetItemImage(item, 0, which=wx.TreeItemIcon_Normal)  # wx.TreeItemIcon_Expanded

            for i, sub_item_dict in enumerate(items):
                #college = lastList[index]  # TreeItemData是每一个ChildItem的唯一标示
                # 以便在点击事件中获得点击项的位置信息
                # "The TreeItemData class no longer exists, just pass your object directly to the tree instead
                # data = wx.TreeItemData(cityID + "|" + str(index))
                sub_item = self.AppendItem(item, str(i), data=sub_item_dict['名称'])
                for j, col in enumerate(self.cols):

                    self.SetItemText(sub_item, sub_item_dict.get(col, ''), j)
                self.SetItemImage(sub_item, 0, which=wx.TreeItemIcon_Normal)  # wx.TreeItemIcon_Expanded
        self.Expand(self.root)

class RuleGrid(wx.grid.Grid):
    def __init__(self,parent):
        super(RuleGrid, self).__init__(parent, -1)

    def add_row(self):
        wx.grid.GridTableMessage(self,
                             wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED
        , 1#插入一行记录
        )

    def del_row(self,index):
        wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED,
                             index,
                                 #改行所在的索引只删除一行
        )


class PandasGrid(wx.grid.Grid):
    def __init__(self,parent,nrow=10,ncol=20):
        super().__init__(parent,-1)
        self.CreateGrid(numRows=nrow, numCols=ncol)

    def show_df(self,df):
        self.ClearGrid()
        self.df = df

        self.SetRowSize(0, 60)
        self.SetColSize(0, 150)

        for i,col in enumerate(list(df.columns)):
            self.SetColLabelValue(i,col)

        if type(df.index) is pd.MultiIndex:
            for i, row in enumerate(list(df.index)):
                self.SetRowLabelValue(i, str(df.index))
        else:
            for i,row in enumerate(list(df.index)):
                self.SetRowLabelValue(i, str(row))

        i = 0
        for index, row in df.iterrows():
            for j in range(len(row)):
                self.SetCellValue(i,j,str(row[j]))
            i += 1

import wx

import matplotlib
#matplotlib.use("WXAgg")
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

class MatplotlibPanel(wx.ScrolledWindow):
    def __init__(self,parent,id=-1):
        super(MatplotlibPanel, self).__init__(parent,id)

        self.TopBoxSizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.TopBoxSizer)

        self.figure = matplotlib.figure.Figure(figsize=(4, 3))
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.TopBoxSizer.Add(self.canvas, proportion=-10, border=2, flag=wx.ALL | wx.EXPAND)

        self.ax1 = self.figure.add_subplot(221)
        self.ax2 = self.figure.add_subplot(222)
        self.ax3 = self.figure.add_subplot(223)
        self.ax4 = self.figure.add_subplot(224)


    def show_data(self,kwargs):
        self.ax1.clear()
        self.ax2.clear()
        self.ax3.clear()
        self.ax4.clear()
        data = kwargs['equity']
        data.plot(ax=self.ax1)
        self.ax1.grid(True)

        df_years = kwargs['yearly']
        if df_years is not None:
            print(df_years)
            df_years.T.plot(kind='bar',ax=self.ax2,use_index=True)
            #sns.barplot(x, y, palette="BuPu_r")

        df_ratio = kwargs['ratio']
        if df_ratio is not None:
            print(df_ratio)
            table = self.ax3.table(cellText=df_ratio.values,
                      cellLoc='center',
                      cellColours=None,
                      rowLabels=df_ratio.index,
                      #rowColours=plt.cm.BuPu(np.linspace(0, 0.5, 5))[::-1],  # BuPu可替换成其他colormap
                      colLabels=df_ratio.columns,
                      #colColours=plt.cm.Reds(np.linspace(0, 0.5, 5))[::-1],
                      rowLoc='right',
                      loc='bottom',
                      #bbox=[0, -0.4, 1, 0.4],
                      )
            table.scale(1, 2)
            self.ax3.axis('off')


        df_corr = kwargs['corr']
        if df_corr is not None:
            #print(df_corr)
            #df_corr.plot(ax=self.ax4)
            sns.heatmap(data=df_corr,
                        annot=True,
                        #vmax=0.3,  # 上图颜色太深，不美观，让整体颜色变浅点
                        ax=self.ax4)
        self.canvas.draw()


if __name__ == '__main__':
    import pandas as pd
    pass




